package com.originskyseed.platform.cms.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.cms.i18n.CmsResponseMsg;
import com.originskyseed.platform.cms.model.Cms;
import com.originskyseed.platform.cms.model.CmsRelateIsRead;
import com.originskyseed.platform.cms.service.ICmsRelateIsReadService;
import com.originskyseed.platform.cms.service.ICmsService;
import com.originskyseed.platform.cms.vo.request.CmsRelateIsReadRequestVO;
import com.originskyseed.platform.common.annotation.SysLog;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.util.bean.ExportExcelUtil;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IUserInfoService;

/**
 * 新闻关联人员是否阅读表Controller类（OSI_CMS_RELATE_IS_READ）
 *
 * @author wlj
 */
@Controller
@RequestMapping("/cmsRelateIsRead")
@BaseLocaleResource(localeFileName = "i18n_cms")
public class CmsRelateIsReadController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CmsRelateIsReadController.class);

	@DubboReference
	private ICmsRelateIsReadService cmsRelateIsReadService;

	@DubboReference
	private ICmsService cmsService;

	@DubboReference
	private IUserInfoService userInfoService;

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cmsRelateIsReadList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<CmsRelateIsRead>> cmsRelateIsReadList(HttpServletRequest request) {
		BaseResponseBody<BasePage<CmsRelateIsRead>> result = null;
		try {
			// 请求对象
			CmsRelateIsReadRequestVO requestVO = this.getParameterBean(CmsRelateIsReadRequestVO.class);

			// 分页查询
			BasePage<CmsRelateIsRead> page = new BasePage<CmsRelateIsRead>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.cmsRelateIsReadService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<CmsRelateIsRead>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<CmsRelateIsRead>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cmsRelateIsReadSave.json", method = RequestMethod.POST)
	@RequiredParams(names = {})
	public BaseResponseBody<CmsRelateIsRead> cmsRelateIsReadSave(HttpServletRequest request) {
		BaseResponseBody<CmsRelateIsRead> result = null;
		try {
			// 请求对象
			CmsRelateIsRead cmsRelateIsRead = this.getParameterBean(CmsRelateIsRead.class);

			if (StringUtils.isNotBlank(cmsRelateIsRead.getId())) {
				this.cmsRelateIsReadService.updateByPrimaryKey(cmsRelateIsRead);
			} else {
				this.cmsRelateIsReadService.insertSelective(cmsRelateIsRead);
			}
			result = new BaseResponseBody<CmsRelateIsRead>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_CONTENT_SAVE_SUCCESS.getMsg()), cmsRelateIsRead);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<CmsRelateIsRead>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_CONTENT_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cmsRelateIsReadDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> cmsRelateIsReadDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.cmsRelateIsReadService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 通知公告阅读情况导出
	 * 
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/exportExcel.json")
	@SysLog(module = "通知公告", operationDesc = "通知公告阅读情况信息")
	public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 请求对象
			String id = this.getParameterString("id", null);// 新闻ID
			Cms cms = this.cmsService.selectByPrimaryKey(id);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			List<CmsRelateIsRead> list = null;
			// OW
			if (userInfo.getSourceSys() == 0) {
				CmsRelateIsRead cmsRelateIsRead = new CmsRelateIsRead();
				cmsRelateIsRead.setCmsId(id);
				list = this.cmsRelateIsReadService.selectCmsRelateReadList(cmsRelateIsRead);
			}
			// excel标题
			String[] title = { "查看维度", "查看人信息", "查看状态", "查看时间" };
			// excel文件名
			String fileName = "通知公告阅读情况" + System.currentTimeMillis() + ".xls";
			// sheet名
			String sheetName = "通知阅读情况";
			String[][] values = new String[list.size()][];

			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					values[i] = new String[title.length];
					CmsRelateIsRead obj = list.get(i);
					UserInfo info = this.userInfoService.selectByPrimaryKey(obj.getObjId());
					values[i][0] = obj.getDeptName();
					values[i][1] = obj.getObjName();
					if (obj.getIsRead() == 1) {
						values[i][2] = "是";
					} else if (obj.getIsRead() == 2) {
						values[i][2] = "否";
					} else {
						values[i][2] = " ";
					}
					values[i][3] = obj.getUpdateTime() == null ? "" : format.format(obj.getUpdateTime());
				}
			}
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 输出Excel
	 *
	 * @param response
	 * @param title
	 * @param fileName
	 * @param sheetName
	 * @param values
	 * @throws IOException
	 */
	private void outPutExcel(HttpServletResponse response, String[] title, String fileName, String sheetName, String[][] values) throws IOException {
		// 创建HSSFWorkbook
		HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
		// 将文件存到指定位置
		this.setResponseHeader(response, fileName);
		OutputStream os = response.getOutputStream();
		wb.write(os);
		os.flush();
		os.close();
	}

	/**
	 * 发送响应流方法
	 *
	 * @param response
	 * @param fileName
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage(), ex);
		}
	}

}
